//
//  WebViewController.swift
//  UserApp_iOS
//
//  Created by linlin on 2019/9/16.
//  Copyright © 2019 linlin. All rights reserved.
//

import UIKit
import WebKit

class WebViewController: BaseViewController, WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler {
    
    var webView: WKWebView!
    var webUrl: String!
    var userContentController: WKUserContentController!
    var hasPaid: Bool = false
    var showBack: Bool = true
    var webTitle: String?

    static func show(from vc: UIViewController?, webUrl: String, title: String? = nil, showBack: Bool = true) -> Void {
        if vc == nil {
            return
        }
        
        if webUrl.count == 0 {
            return
        }
        
        let webVC: WebViewController = WebViewController()
        webVC.webUrl = webUrl
        webVC.webTitle = title
        webVC.showBack = showBack
        
        vc?.show(webVC, sender: vc)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        title = webTitle ?? "云配商城"
        initWebView()
        loadRequest()
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        
//        webView.height = view.height
    }
    
    deinit {
        userContentController?.removeAllUserScripts()
    }
    
    func initWebView() -> Void {
        let configuration = WKWebViewConfiguration()
        let preferences = WKPreferences()
        preferences.javaScriptEnabled = true
        configuration.preferences = preferences
        userContentController = WKUserContentController()
        userContentController.add(self, name: "goHome")
        userContentController.add(self, name: "share")
        userContentController.add(self, name: "goChat")
        userContentController.add(self, name: "goBack")
        configuration.userContentController = userContentController
        webView = WKWebView(frame: view.bounds, configuration: configuration)
        webView.navigationDelegate = self
        webView.uiDelegate = self as WKUIDelegate
        view.addSubview(webView)
        
        let closeItem = UIBarButtonItem(image: UIImage(named: "icon_close"), style: .plain, target: self, action: #selector(closeAction))
        let backItem = UIBarButtonItem(image: UIImage(named: "ic_back"), style: .plain, target: self, action: #selector(backAction))
        let refreshItem = UIBarButtonItem(image: UIImage(named: "icon_refresh"), style: .plain, target: self, action: #selector(refreshAction))
        navigationItem.leftBarButtonItems = showBack ? [backItem, closeItem] : [closeItem]
        navigationItem.rightBarButtonItem = refreshItem
    }
    
    @objc func refreshAction() {
        webView.reload()
    }
    
    @objc func backAction() {
        if webView.canGoBack {
            webView.goBack()
        } else {
            closeAction()
        }
    }
    
    @objc func closeAction() {
        self.navigationController?.popViewController(animated: true)
    }
    
    @objc func loadRequest() -> Void {
        if webUrl.hasPrefix("http") {
//            webUrl += "&SessionId=\(sessionId ?? "")&"
            let url: URL = URL(string: webUrl)!
            let request: URLRequest = URLRequest(url: url)
            webView.load(request)
        } else {
            var content = webUrl!
            let fileManager: FileManager = .default
            if fileManager.fileExists(atPath: content) {
                content = try! String.init(contentsOfFile: content, encoding: .utf8)
            }
            webView.loadHTMLString(content, baseURL: nil)
        }
        
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        let urlStr = navigationAction.request.url?.absoluteString
        debugPrint(navigationAction.navigationType.rawValue)
        if (urlStr?.hasPrefix("weixin://wap/pay") ?? false) || (urlStr?.hasPrefix("alipay://alipayclient") ?? false){
            guard !hasPaid else {
                decisionHandler(.allow)
                return
            }
            
            hasPaid = true
            let url: URL = URL(string: urlStr!)!
            UIApplication.shared.open(url, options: [UIApplication.OpenExternalURLOptionsKey.universalLinksOnly : false]) { (isOpened) in
                debugPrint(isOpened)
            }
            decisionHandler(.cancel)
        } else {
            if !(urlStr?.elementsEqual(webUrl+"#") ?? false) {
//                DialogUtil.showProgress()
            }
            decisionHandler(.allow)
        }
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
//        DialogUtil.closeProgress()
        if webView.title!.count > 0 {
            
            title = webView.title
        }
    }
    
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
//        DialogUtil.closeProgress()
//        DialogUtil.showToast(message: error.localizedDescription)
    }
    
    //webview ui delegate
    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
        if let targetFrame = navigationAction.targetFrame, !targetFrame.isMainFrame {
            webView.load(navigationAction.request)
        }
        
        return nil
    }
    
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
//        DialogUtil.showAlert(title: nil, message: message, context: self) {
//            completionHandler()
//        }
    }
    
    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
//        DialogUtil.showAlert(title: nil, message: message, context: self) {
//            completionHandler(true)
//        }
    }
    
    // MARK -JS MESSAGE
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        switch message.name {
        case "goHome":
            goHome()
        case "share":
            share(body: message.body)
        case "goChat":
            goChat(body: message.body)
        case "goBack":
            closeAction()
        default:
            return
        }
    }
    
    func share(body: Any) {
        if let content = body as? String {
            do {
                content.filter { (c) -> Bool in
                    return c == "\\"
                }
                let dic = try JSONSerialization.jsonObject(with: content.data(using: .utf8)!, options: .allowFragments) as? [String:Any]
                guard let _ = dic else { return }
                
               
            } catch let error {
                debugPrint(error)
            }
        }
    }
    
    func goHome() {
        self.navigationController?.popToRootViewController(animated: true)
        self.tabBarController?.selectedIndex = 0
    }
    
    func goChat(body:Any) {
        if let userId = body as? Int {
            
        } else if let userId = body as? String {
           
        }
    }
}
